package com.xgame.server.utils;

import com.xgame.server.handler.Handler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class HandlerRegister implements InitializingBean, ApplicationContextAware {


    private Map<String, Handler> serviceImplMap = new HashMap<>();
    private ApplicationContext applicationContext;


    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, Handler> beanMap = applicationContext.getBeansOfType(Handler.class);
        // 以下代码是将bean按照自己定的规则放入map中，这里我的规则是key：service.toString();value:bean
        // 调用时，参数传入service.toString()的具体字符串就能获取到相应的bean
        // 此处也可以不做以下的操作，直接使用beanMap,在调用时，传入bean的名称
        for (Handler serviceImpl : beanMap.values()) {
            serviceImplMap.put(lowerFirst(serviceImpl.getClass().getSimpleName()), serviceImpl);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public Handler getHandlerImpl(String name) {
        return serviceImplMap.get(name);
    }

    private  String lowerFirst(String oldStr){

        char[]chars = oldStr.toCharArray();

        chars[0] += 32;

        return String.valueOf(chars);

    }
}
